package com.example.springevent.event.methodlistener;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import com.example.springevent.event.bo.IvdAddedEventBO;
import com.example.springevent.event.bo.IvdRemovedEventBO;
import com.example.springevent.event.event.IvdAddedEvent;

//@Component
public class IvdEventListenerPoHandler {

	private static final Logger log = LoggerFactory.getLogger(IvdEventListenerPoHandler.class);

	@EventListener
	@Async
	public void handleIvdAddedEvent(IvdAddedEvent event) {
		log.info("事件监听handleIvdAddedEvent。Thread={}:", Thread.currentThread().getName());
		IvdAddedEventBO ivd = event.getIvdAddedEventBO();
		addVerifyAmt(ivd.getPoCode(), ivd.getVerifyAmt());
	}

	@EventListener
	public void handleIvdRemovedEvent(IvdRemovedEventBO ivd) {
		log.info("事件监听handleIvdRemovedEvent。Thread={}:", Thread.currentThread().getName());
		addVerifyAmt(ivd.getPoCode(), ivd.getVerifyAmt().negate());
	}

	@TransactionalEventListener(
			classes = IvdRemovedEventBO.class, 
			phase = TransactionPhase.AFTER_COMMIT, 
			fallbackExecution = true)
	public void handleIvdRemovedEventInTran(IvdRemovedEventBO ivd) {
		log.info("事件监听handleIvdRemovedEventInTran。Thread={}:", Thread.currentThread().getName());
		addVerifyAmt(ivd.getPoCode(), ivd.getVerifyAmt().negate());
	}

	public void addVerifyAmt(String poCode, BigDecimal verifyAmt) {
		log.info("订单[{}]增加核销金额[{}]", poCode, verifyAmt);
	}
}
